import { http } from '../http/axios';
import { ENDPOINTS } from '../constants/endpoints';
import type {
  Material,
  CreateMaterialRequest,
  UpdateMaterialRequest
} from '../types/material';
export const materialService = {
  // 获取物资列表
  getMaterials: async (): Promise<Material[]> => {
    const response = await http.get(ENDPOINTS.MATERIAL.LIST);
    return response.data;
  },

  // 获取单个物资
  getMaterial: async (id: number): Promise<Material> => {
    const response = await http.get(ENDPOINTS.MATERIAL.DETAIL(id));
    return response.data;
  },

  createMaterial: async (data: CreateMaterialRequest): Promise<Material> => {
    const response = await fetch('http://localhost:8082/materials', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) {
      throw new Error('新增物资失败');
    }
    return response.json();
  },

  // 更新物资
  updateMaterial: async (id: number, data: UpdateMaterialRequest): Promise<Material> => {
    const response = await http.put(ENDPOINTS.MATERIAL.UPDATE(id), data);
    return response.data;
  },

  deleteMaterial: async (id: number): Promise<void> => {

    try {
      const response = await http.delete(ENDPOINTS.MATERIAL.DELETE(id));

    } catch (error: any) {
      const serverError = error.response?.data?.error ||
        error.response?.data?.message ||
        '删除物资失败';
      throw new Error(serverError);
    }
  },
};